<template>
  <a-modal :open="open" title="提取的数据" width="1000px" :footer="null" @cancel="handleCancel" :maskClosable="false">
    <div class="extracted-data-container">
      <div class="field-type-selector">
        <a-select :value="fieldType" @change="handleFieldTypeChange" style="width: 100%; margin-bottom: 16px;">
          <a-select-option value="query">查询字段</a-select-option>
          <a-select-option value="list">列表字段</a-select-option>
          <a-select-option value="custom">自定义</a-select-option>
        </a-select>
      </div>

      <!-- 自定义模式输入框 -->
      <div v-if="fieldType === 'custom'" class="custom-field-inputs" style="margin-bottom: 16px; display: flex; gap: 16px;">
        <a-input 
          v-model:value="customLabelKey" 
          placeholder="请输入label的key" 
          maxlength="8"
          @blur="handleCustomKeyChange"
          style="flex: 1;"
        />
        <a-input 
          v-model:value="customValueKey" 
          placeholder="请输入value的key" 
          maxlength="8"
          @blur="handleCustomKeyChange"
          style="flex: 1;"
        />
      </div>

      <codemirror
        v-model="formattedData"
        :style="{ height: '400px' }"
        :autofocus="true"
        :indent-with-tab="true"
        :tab-size="2"
        :extensions="extensions"
      />

      <div class="copy-button-container">
        <a-button type="primary" @click="copyToClipboard" :loading="copying">
          {{ copying ? '复制中...' : '复制到剪贴板' }}
        </a-button>
        <span v-if="copySuccess" class="copy-success">复制成功!</span>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { json } from '@codemirror/lang-json'
// import { oneDark } from '@codemirror/theme-one-dark'

// 代码编辑器扩展配置
const extensions = [json()]

const props = defineProps({
  open: {
    type: Boolean,
    required: true
  },
  data: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:open'])

// 字段类型：query-查询字段, list-列表字段, custom-自定义
const fieldType = ref('query')
const copying = ref(false)
const copySuccess = ref(false)

// 自定义键名
const customLabelKey = ref('label')
const customValueKey = ref('value')

const formattedData = computed(() => {
  if (fieldType.value === 'query') {
    // 查询字段格式：[{label: "描述", field: "参数名"}]
    const queryData = props.data.map(item => ({
      label: item.label,
      field: item.value
    }))
    return JSON.stringify(queryData, null, 2)
  } else if (fieldType.value === 'list') {
    // 列表字段格式：[{title: "描述", key: "参数名"}]
    const listData = props.data.map(item => ({
      title: item.label,
      key: item.value
    }))
    return JSON.stringify(listData, null, 2)
  } else {
    // 自定义字段格式：[{[customLabelKey]: "描述", [customValueKey]: "参数名"}]
    const customData = props.data.map(item => ({
      [customLabelKey.value]: item.label,
      [customValueKey.value]: item.value
    }))
    return JSON.stringify(customData, null, 2)
  }
})

const handleCancel = () => {
  emit('update:open', false)
}

const handleFieldTypeChange = (value) => {
  fieldType.value = value
  
  // 当切换到自定义模式时，重置自定义键名为初始值
  if (value === 'custom') {
    customLabelKey.value = 'label'
    customValueKey.value = 'value'
  }
}

const handleCustomKeyChange = () => {
  // 失去焦点时不需要特殊处理，computed会自动更新
}

const copyToClipboard = async () => {
  copying.value = true
  copySuccess.value = false

  try {
    // 检查浏览器是否支持Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(formattedData.value)
      copySuccess.value = true
    } else {
      // 降级处理：使用传统的execCommand('copy')方法
      const textArea = document.createElement('textarea')
      textArea.value = formattedData.value
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()

      const successful = document.execCommand('copy')
      document.body.removeChild(textArea)

      if (successful) {
        copySuccess.value = true
      } else {
        throw new Error('execCommand failed')
      }
    }

    // 3秒后隐藏成功提示
    setTimeout(() => {
      copySuccess.value = false
    }, 3000)
  } catch (err) {
    console.error('复制失败:', err)
    alert('复制失败，请手动复制')
  } finally {
    copying.value = false
  }
}
</script>

<style scoped>
.extracted-data-container {
  /* max-height: 60vh; */
  overflow-y: auto;
  padding: 15px;
}

.field-type-selector {
  text-align: left;
}

.custom-field-inputs :deep(.ant-input) {
  text-align: left;
}

.copy-button-container {
  margin-top: 16px;
  text-align: center;
  position: relative;
}

.copy-success {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  color: #52c41a;
  font-weight: bold;
  animation: fadeInOut 3s ease-in-out;
}

@keyframes fadeInOut {

  0%,
  100% {
    opacity: 0;
  }

  20%,
  80% {
    opacity: 1;
  }
}
</style>